import {
  getFlowTable
} from '../../api/financial'
import {
  FLOW_LIST,
  FLOW_SUM_DATA,
  FLOW_DATA_COUNT,
  FLOW_HISTORY_DATA,
  FLOW_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    flowList: [],
    flowSumData: [],
    flowDataCount: null,
    flowPageSize: 10,
    flowHistoryData: [],
    row: {
      businesstime: '',
      name: '',
      phone: '',
      message: '',
      consumetype: '',
      cost: ''
    }
  },
  getters: {
    flowList: state => state.flowList
  },
  mutations: {
    [FLOW_LIST] (state, data) {
      state.flowList = data
    },
    [FLOW_SUM_DATA] (state, data) {
      state.flowSumData = data
    },
    [FLOW_DATA_COUNT] (state, data) {
      state.flowDataCount = data
    },
    [FLOW_HISTORY_DATA] (state, data) {
      state.flowHistoryData = data
    },
    [FLOW_PAGE_SIZE] (state, data) {
      state.flowPageSize = data
    }
  },
  actions: {
    async getFlowList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      let sumData = []
      let income = 0
      let account = 0
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getFlowTable(data)
      const res = await getFlowTable({})
      res.data.data.rows.map((item) => {
        if (item.type === 0 || item.type === 1) {
          income += item.money
        } else {
          account += item.money
        }
        sumData = [...sumData, {
          income: income,
          account: account
        }]
      })
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id,
          ctime: item.ctime,
          name: item.name,
          phone: item.phone,
          des: item.des,
          type: item.type,
          money: item.money,
          income: income,
          account: account
        }]
      })
      commit(FLOW_LIST, newData)
      commit(FLOW_SUM_DATA, sumData)
      commit(FLOW_DATA_COUNT, newData.length)
      if (newData.length < rootState.flow.flowPageSize) {
        commit(FLOW_HISTORY_DATA, newData)
      } else {
        commit(FLOW_HISTORY_DATA, newData.slice(0, rootState.flow.flowPageSize))
      }
    },
    async changeFlowPage ({ commit, rootState }, index) {
      let data = rootState.flow.flowList
      let _start = (index - 1) * rootState.flow.flowPageSize
      let _end = index * rootState.flow.flowPageSize
      commit(FLOW_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeFlowPageSize ({ commit, rootState }, value) {
      commit(FLOW_PAGE_SIZE, value)
    }
  }
}
